﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using S1882I;
using System.IO;
using System.Globalization;


namespace card
{
    public partial class Frm_cargo_card : Form
    {
        
        S1882IReWr rw = new S1882IReWr();

        public static WebDG.Service ws = new card.WebDG.Service();
        string shipname = "";
        string cargoname = "";
        string yard = "";
        string stackname = "";
        string shipper_name = "";
        string cargono = "0";

        //string logintime = "";
        string ioyardid = "1";//市入//待确认0或1
        string str_operator = "";
        string plan_code = "1";//有计划作业

        string truckno = "";
        string truckcolor = "";
        string drivername = "";
        string driverid = "";
        string driverphone = "";

        string pieces = "";
        string weight = "";
        string standards = "";
        string bzbz = "";
        string bill_no = "";
        string voyage = "";

        string qdcardnum = "";

        string grid_sel = "";//dengji//zhiling

        //string cardadd = "东门";
        public string cardadd
        {
            get;
            set;
        }
        public string io_port
        {
            get;
            set;
        }

        string str_cur_date = "";
        string str_pre_date = "";

        public Frm_cargo_card()
        {
            InitializeComponent();
        }

        public static OracleDatabase db =
           new OracleDatabase("Data Source=sjzx;User ID=dbcenter;Password=ok;Unicode=True;Load Balance Timeout=1000");

        private void Frm_cargo_card_Load(object sender, EventArgs e)
        {
            Rectangle rect = new Rectangle();
            rect = Screen.GetWorkingArea(this);
            dataGridView1.Width = rect.Width - 20;
            dataGridView1.Height = rect.Height - dataGridView1.Top - panel2.Height - 50;
            panel2.Top = dataGridView1.Top + dataGridView1.Height;
            //connect_card();

           // FileStream aFile = new FileStream(@"C:\truck_login_id.ini", FileMode.Open);
           // StreamReader sr = new StreamReader(aFile);//用FileStream对象实例化一个StreamReader对象,若全部为英文，可用这种方式
           // string strLine1 = sr.ReadLine();//   读取一行字符并返回
           // sr.Close();
           // if (strLine1 == "0")
           // {
           //     connect_card();
           // }
            listBox1.Visible = false;


            grid_sel = "zhiling";
            button1.Enabled = true;

            checkBox1.Checked = false;
            str_operator = this.Text.Substring(6);
            //MessageBox.Show(str_operator);

            //DateTime date_temp=DateTime.Now.Date; 
            //txtdate.Text  =date_temp .ToShortDateString ();
            string sqlStr = "select sysdate from dual";
            DataSet ds = ws.getDataSet_Serv(sqlStr);
            //DataTable dt = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString())).Tables[0];
            //DataSet ds = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString()));
            if (ds.Tables[0].Rows.Count > 0)
            {
                str_cur_date = ds.Tables[0].Rows[0][0].ToString();
            }
            dateTimePicker1.Value = Convert.ToDateTime(str_cur_date);

            dataGridView1.ReadOnly = true;
            dataGridView1.AllowUserToAddRows = false;
            dataGridView1.AllowUserToDeleteRows = false;

            str_cur_date = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            str_pre_date = dateTimePicker1.Value.AddDays(-1).ToString("yyyy-MM-dd");
            refresh_grid();
        }

        private void refresh_grid()
        {
            string sqlStr = "select truckno as 车号,qdcardnum as 卡号,SHIPNAME as 船名,voyage as 航次,bill_no as 提单号,cargoname as 货名,stackname as 垛名货品名称,yard as 装货地点,pieces as 件数,weight as 重量,standards as 规格,shipper_name as 货主,cargono as 货号,remark as 备注,commandtime as 发指令时间 from truck_login ";
            if (txt_cargo_sel.Text.Length == 0)
            {
                if (checkBox1.Checked == true)
                {
                    if (grid_sel == "zhiling")
                    {
                        sqlStr = sqlStr + "where IOYARDID='" + ioyardid + "' and truckstatus='1' and cardadd='" + cardadd + "'";
                    }
                    else
                    {
                        sqlStr = sqlStr + "where IOYARDID='" + ioyardid + "' and truckstatus='0' and cardadd='" + cardadd + "'";
                    }
                }
                else
                {
                    if (grid_sel == "zhiling")
                    {
                        sqlStr = sqlStr + " where to_char(logintime,'yyyy-mm-dd HH24:MI:SS')>='" + str_pre_date + " 23:59:59" + "' AND to_char(logintime,'yyyy-mm-dd HH24:MI:SS')<='" + str_cur_date + " 23:59:59" + "' AND IOYARDID='" + ioyardid + "' and truckstatus='1' and cardadd='" + cardadd + "'";
                    }
                    else
                    {
                        sqlStr = sqlStr + " where  to_char(logintime,'yyyy-mm-dd HH24:MI:SS')>='" + str_pre_date + " 23:59:59" + "' AND to_char(logintime,'yyyy-mm-dd HH24:MI:SS')<='" + str_cur_date + " 23:59:59" + "' AND IOYARDID='" + ioyardid + "' and truckstatus='0' and cardadd='" + cardadd + "'";
                    }
                }
            }
            else
            {
                if (checkBox1.Checked == true)
                {
                    if (grid_sel == "zhiling")
                    {
                        sqlStr = sqlStr + " where IOYARDID='" + ioyardid + "' and truckno like '%" + txt_cargo_sel.Text.Trim() + "%' and truckstatus='1' and cardadd='" + cardadd + "'";
                    }
                    else
                    {
                        sqlStr = sqlStr + " where IOYARDID='" + ioyardid + "' and truckno like '%" + txt_cargo_sel.Text.Trim() + "%' and truckstatus='0' and cardadd='" + cardadd + "'";
                    }
                }
                else
                {
                    if (grid_sel == "zhiling")
                    {
                        sqlStr = sqlStr + " where  to_char(logintime,'yyyy-mm-dd HH24:MI:SS')>='" + str_pre_date + " 23:59:59" + "' AND to_char(logintime,'yyyy-mm-dd HH24:MI:SS')<='" + str_cur_date + " 23:59:59" + "' AND IOYARDID='" + ioyardid + "' and truckno like '%" + txt_cargo_sel.Text.Trim() + "%' and truckstatus='1' and cardadd='" + cardadd + "'";
                    }
                    else
                    {
                        sqlStr = sqlStr + " where  to_char(logintime,'yyyy-mm-dd HH24:MI:SS')>='" + str_pre_date + " 23:59:59" + "' AND to_char(logintime,'yyyy-mm-dd HH24:MI:SS')<='" + str_cur_date + " 23:59:59" + "' AND IOYARDID='" + ioyardid + "' and truckno like '%" + txt_cargo_sel.Text.Trim() + "%' and truckstatus='0' and cardadd='" + cardadd + "'";
                    }
                }
            }
            sqlStr = sqlStr + " order by logintime desc";

            DataSet ds = ws.getDataSet_Serv(sqlStr);
            //DataTable dt2 = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString())).Tables[0];
            //DataSet ds = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString()));

            dataGridView1.DataSource = ds.Tables[0];

            int i = 0;
            for (i = 0; i < 15; i++)
            {
                dataGridView1.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
            txt_drivername.Text = "";
            txt_id.Text = "";
            txt_phone.Text = "";

            if (grid_sel == "dengji")
            {
                button1.Enabled = false;
            }
            if (grid_sel == "zhiling")
            {
                button1.Enabled = true;
            }
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            str_cur_date = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            str_pre_date = dateTimePicker1.Value.AddDays(-1).ToString("yyyy-MM-dd");
            //refresh_grid();
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            refresh_grid();
        }
        private int check_message()
        {
            qdcardnum = txt_qdcardnum.Text;
            if (qdcardnum.Length > 5)
            {
                MessageBox.Show("卡号输入长度超长，请重新输入（少于10个数字）。");
                txt_qdcardnum.Focus();
                return 0;
            }
            return 1;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string cardtime = "";
            string STR_CARDNO = "";//卡的EPCID号

            string str_tid = read_TID();
            string sqlStr = "select cardid from card_admin where cardid='" + str_tid + "'";
            DataSet ds111 = ws.getDataSet_Serv(sqlStr);
            if (ds111.Tables[0].Rows.Count > 0)
            {
            }
            else
            {
                MessageBox.Show("该卡没有进行登记，不能进行写卡。");
                return;
            }

            string truck_epcid = "";
            sqlStr = "select seq_truck_card_epcid.nextval from dual";
            DataSet ds1 = ws.getDataSet_Serv(sqlStr);
            if (ds1.Tables[0].Rows.Count > 0)
            {
                truck_epcid = ds1.Tables[0].Rows[0][0].ToString();
            }
            STR_CARDNO = truck_epcid;

            if (driverphone.Length <= 0)
            {
                MessageBox.Show("请选择车辆。");
            }
            else
            {
                if (check_message() == 1)
                {
                    int i_truckinfo = WRITE_TRUCKINFO(ioyardid + " " + truckno);
                    int i_temp = 0;
                    if (i_truckinfo == 0)
                    {
                        while (i_temp < 6)
                        {
                            i_truckinfo = WRITE_TRUCKINFO(ioyardid + " " + truckno);
                            if (i_truckinfo == 0)
                            {
                                i_temp = i_temp + 1;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (i_temp == 6)
                        {
                            MessageBox.Show("写入车号信息失败。");
                            return;
                        }
                    }
                    int i_truck_epcid = write_truck_epcid(truck_epcid);
                    i_temp = 0;
                    if (i_truck_epcid == 0)
                    {
                        while (i_temp < 6)
                        {
                            i_truck_epcid = write_truck_epcid(truck_epcid);
                            if (i_truck_epcid == 0)
                            {
                                i_temp = i_temp + 1;
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (i_temp == 6)
                        {
                            MessageBox.Show("写入车卡EPCID信息失败。");
                            return;
                        }
                    }

                    //int i_truckinfo=WRITE_TRUCKINFO(ioyardid + " " + truckno);
                    //if (i_truckinfo == 0)
                    //{
                    //    MessageBox.Show("写入车号信息失败。");
                    //    return;
                    //}
                    //int i_truck_epcid = write_truck_epcid(truck_epcid);
                    //if (i_truck_epcid == 0)
                    //{
                    //    MessageBox.Show("写入车卡EPCID信息失败。");
                    //    return;
                    //}

                    //string str_truckinfo_temp = read_truckinfo();
                    //if (str_truckinfo_temp == "-1")
                    //{
                    //    MessageBox.Show("读取车号信息失败。");
                    //    return;
                    //}
                    //string str_truck_epcid_temp = read_truck_epcid();
                    //if (str_truck_epcid_temp == "-1")
                    //{
                    //    MessageBox.Show("读取车卡EPCID信息失败。");
                    //    return;
                    //}
                    MessageBox.Show("已写入车卡信息：" + ioyardid + " " + truckno);

                    sqlStr = "select sysdate from dual";
                    ds1 = ws.getDataSet_Serv(sqlStr);
                    //DataTable dt1 = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString())).Tables[0];
                    //DataSet ds1 = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString()));
                    if (ds1.Tables[0].Rows.Count > 0)
                    {
                        cardtime = ds1.Tables[0].Rows[0][0].ToString();
                    }

                    string StrSql1 = "update truck_login set cardtime=sysdate,TRUCKSTATUS='2',CARDNO='" + STR_CARDNO + "',qdcardnum='" + qdcardnum + "' where TRUCKNO='" + truckno + "' AND IOYARDID='" + ioyardid + "'";
                    int ret1 = ws.execute_UID_Serv(StrSql1);

                    string card_add = "";
                    string sqlStr1 = "select cardadd from truck_login where TRUCKNO='" + truckno + "' AND IOYARDID='" + ioyardid + "'";
                    DataSet ds11 = ws.getDataSet_Serv(sqlStr1);
                    if (ds11.Tables[0].Rows.Count > 0)
                    {
                        card_add = ds11.Tables[0].Rows[0][0].ToString();
                    }
                    if (card_add == "西门")
                    {
                        string StrSql11 = "update truck_login set doorintime=sysdate,TRUCKSTATUS='3' where TRUCKNO='" + truckno + "' AND IOYARDID='" + ioyardid + "'";
                        int ret11 = ws.execute_UID_Serv(StrSql11);
                    }
                    //MessageBox.Show(StrSql);
                    //int ret1 = db.ExecuteNonQuery(db.GetSqlStringCommand(StrSql1.ToString()));
                    if (ret1 == 1)
                    {
                        //MessageBox.Show("更新数据库成功。");
                    }
                    else
                    {
                        //MessageBox.Show("更新数据库失败。");
                        //return;
                    }

                }
            }
            refresh_grid();
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            
            this.Close();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                dateTimePicker1.Enabled = false;
            }
            else
            {
                dateTimePicker1.Enabled = true;
            }
            //refresh_grid();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            
        }

        private void connect_card()
        {
            short by = rw.Connect_Open(io_port);
            if (by == 0)
            {
                //write_ini();
            }
            //MessageBox.Show (DateTime.Now + "  提示:连接读写器成功.\r\n");
            else
            {
                MessageBox.Show(DateTime.Now + String.Format("  错误:读写器连接失败:{0:X}.", by) + "\r\n"); 
            }
            //rtLog.ScrollToCaret(); 
        }

        private int  WRITE_TRUCKINFO(string info)
        {
            connect_card();
            int i_return = 0;
            string data = ConvertTools.ToHex(info , "UTF-8");
            //short by = rw.WriteUser(data);
            short by = rw.WriteUser(data);
            if (by == 0)
                //MessageBox.Show(DateTime.Now + "  写入车辆信息成功！\r\n");
                i_return = 1;
            //byte[] tagsid = rw.ReadID().tags_id;
            else
                i_return = 0;
                //MessageBox.Show(DateTime.Now + String.Format("  写入车辆信息失败:{0:X}.", by) + "\r\n");
            //rtLog.ScrollToCaret();
            disconnect_card();
            return i_return;
        }
        private int  write_truck_epcid(string info)
        {
            connect_card();
            int i_return = 0;
            string data = info;
            short by = rw.WriteID(data);
            if (by == 0)
                i_return = 1;
            //MessageBox.Show(DateTime.Now + "  写入EPCID成功！\r\n");
            //byte[] tagsid = rw.ReadID().tags_id;
            else
                i_return = 0;
                //MessageBox.Show(DateTime.Now + String.Format("  写入EPCID失败:{0:X}.", by) + "\r\n");
            //rtLog.ScrollToCaret();
            disconnect_card();
            return i_return;
        }
        private string read_truck_epcid()
        {
            connect_card();
            string str_return="";
            TagCountId tc = rw.ReadID();
            if (tc.iDBitCount > 0)
            {
                string strid = "";
                for (int j = 1; j <= tc.tags_id[0]; j++)
                {
                    strid += String.Format("{0:X02}", tc.tags_id[j]);
                }
                str_return = strid.Substring(6);
                //rtLog.AppendText(DateTime.Now + "  读到的标签:" + strid + "\r\n");
            }
            else
                str_return = "-1";
                //rtLog.AppendText(DateTime.Now + " 读标签失败！" + "\r\n");
            //rtLog.ScrollToCaret(); 
            disconnect_card();
            return str_return;
        }
        private string read_truckinfo()
        {
            connect_card();
            string str_return = "";
            TagCountId tc = rw.ReadUser();
            if (tc.iDBitCount > 0)
            {
                string strid = "";
                for (int j = 1; j <= tc.tags_id[0]; j++)
                {
                    strid += String.Format("{0:X02}", tc.tags_id[j]);
                }
                strid = ConvertTools.UnHex(strid, "UTF-8");
                str_return = strid;
                //rtLog.AppendText(DateTime.Now + "  读到的标签:" + ConvertTools.UnHex(strid, "UTF-8") + "\r\n");
            }
            else
                str_return = "-1";
                //rtLog.AppendText(DateTime.Now + " 读标签失败！" + "\r\n");
            //rtLog.ScrollToCaret();
            disconnect_card();
            return str_return;
        }
        private void disconnect_card()
        {
            short by = rw.Connect_Close();
            if (by == 0)
            { }
            //  rtLog.AppendText(DateTime.Now + "  提示:读写器断开成功.\r\n");
            else
            {
                MessageBox .Show (DateTime.Now + String.Format("  错误:读写器连接断开失败:{0:X}.", by) + "\r\n");
            }

            //rtLog.ScrollToCaret(); 
        }

        private void Frm_cargo_card_FormClosed(object sender, FormClosedEventArgs e)
        {
            //disconnect_card();
        }
        private void write_ini()
        {
            FileStream aFile = new FileStream(@"C:\truck_login_id.ini", FileMode.Open);
            StreamWriter sw = new StreamWriter(aFile);
            sw.WriteLine("1");
            sw.Close();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listBox1_Click(object sender, EventArgs e)
        {
            txt_cargo_sel .Text  = listBox1.SelectedItem.ToString();
            listBox1.Visible = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            string sqlStr = "select distinct cargoname from truck_login where truckstatus='0' and IOYARDID='" + ioyardid + "'";
            DataSet ds = ws.getDataSet_Serv(sqlStr);
            //DataTable dt2 = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString())).Tables[0];
            //DataSet ds = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString()));
            //listBox1.DataSource = ds;
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    listBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
                }
            }

            listBox1.Visible = true;
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            grid_sel = "dengji";
            //button1.Enabled = false;
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            grid_sel = "zhiling";
            //button1.Enabled = true;
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            int rowindex = e.RowIndex;
            truckno = dataGridView1.Rows[rowindex].Cells[0].Value.ToString();
            shipname = dataGridView1.Rows[rowindex].Cells[1].Value.ToString();
            voyage = dataGridView1.Rows[rowindex].Cells[2].Value.ToString();
            bill_no = dataGridView1.Rows[rowindex].Cells[3].Value.ToString();
            cargoname = dataGridView1.Rows[rowindex].Cells[4].Value.ToString();
            stackname = dataGridView1.Rows[rowindex].Cells[5].Value.ToString();
            yard = dataGridView1.Rows[rowindex].Cells[6].Value.ToString();
            pieces = dataGridView1.Rows[rowindex].Cells[7].Value.ToString();
            weight = dataGridView1.Rows[rowindex].Cells[8].Value.ToString();
            standards = dataGridView1.Rows[rowindex].Cells[9].Value.ToString();
            shipper_name = dataGridView1.Rows[rowindex].Cells[10].Value.ToString();
            cargono = dataGridView1.Rows[rowindex].Cells[11].Value.ToString();
            bzbz = dataGridView1.Rows[rowindex].Cells[12].Value.ToString();

            string sqlStr = "select drivername,driverid,driverphone from truck_login where TRUCKNO='" + truckno + "' AND IOYARDID='" + ioyardid + "'";
            DataSet ds = ws.getDataSet_Serv(sqlStr);
            //MessageBox.Show(StrSql);
            //DataTable dt = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString())).Tables[0];
            //DataSet ds = db.ExecuteDataSet(db.GetSqlStringCommand(sqlStr.ToString()));
            if (ds.Tables[0].Rows.Count > 0)
            {
                drivername = ds.Tables[0].Rows[0][0].ToString();
                driverid = ds.Tables[0].Rows[0][1].ToString();
                driverphone = ds.Tables[0].Rows[0][2].ToString();
            }
            txt_drivername.Text = drivername;
            txt_id.Text = driverid;
            txt_phone.Text = driverphone;
        }

        private void txt_qdcardnum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == System.Windows.Forms.Keys.Enter)
            {
                this.button1.Focus();
            }
        }
        private void SetDataGridViewRowXh(DataGridViewRowPostPaintEventArgs e, DataGridView dataGridView)
        {
            SolidBrush solidBrush = new SolidBrush(dataGridView.RowHeadersDefaultCellStyle.ForeColor);
            int xh = e.RowIndex + 1;
            e.Graphics.DrawString(xh.ToString(CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, solidBrush, e.RowBounds.Location.X + 5, e.RowBounds.Location.Y + 4);
        }

        private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            SetDataGridViewRowXh(e, dataGridView1);

        }
        private string read_TID()
        {
            connect_card();

            string str_return = "";
            TagCountId tc = rw.ReadTID();
            if (tc.iDBitCount > 0)
            {
                string strid = "";
                for (int j = 1; j <= tc.tags_id[0]; j++)
                {
                    strid += String.Format("{0:X02}", tc.tags_id[j]);
                }
                str_return = strid.Substring(6);
                //rtLog.AppendText(DateTime.Now + "  读到的标签:" + strid + "\r\n");
            }
            else
                str_return = "-1";
            //rtLog.AppendText(DateTime.Now + " 读标签失败！" + "\r\n");
            //rtLog.ScrollToCaret(); 
            disconnect_card();
            return str_return;
        }
    }
}
